package com.example.myapplication.utils

import android.os.Handler
import android.os.Looper
import android.os.Message
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import kotlin.concurrent.thread

object NetUtils {
    private val ip = "http://192.168.0.103:8080/"
    fun get(url: String, headers: Headers? = null, handler: Handler) {
        thread {
            val request = if (headers == null) Request.Builder().url(ip + url).get()
                .build() else Request.Builder().headers(headers).url(ip + url).get().build()
            val client = OkHttpClient.Builder().build()
            val response = client.newCall(request).execute()
            handler.sendMessage(Message.obtain().apply {
                obj = response.body?.string()
            })
        }
    }

    fun post(
        url: String,
        headers: Headers? = null,
        requestBody: RequestBody,
        handler: Handler
    ) {
        thread {
            val request = if (headers == null) Request.Builder().url(ip + url).post(requestBody)
                .build() else Request.Builder().headers(headers).url(ip + url).post(requestBody)
                .build()
            val client = OkHttpClient.Builder().build()
            val response = client.newCall(request).execute()
            handler.sendMessage(Message.obtain().apply {
                obj = response.body?.string()
            })
        }
    }
}